/**
 * Copyright ©2016-2022 tianyu education Corporation, All Rights Reserved
 * http://www.whty.com.cn/
 */
package profile.hujia.shiro.study.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import profile.hujia.shiro.study.model.UserDO;
import profile.hujia.shiro.study.service.UserService;

/**
 * HelloController
 *
 * @author hujia
 * @date 2019-12-04 15:28
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/hello/bad")
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String hello() {
        return "hello world";
    }

    @GetMapping("/test")
    public String test() {
        StopWatch stopWatch = new StopWatch("test");
        stopWatch.start();
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("info", userService.getUser("hujia"));
        stopWatch.stop();
        log.debug(stopWatch.shortSummary());
        return "test";
    }

    @GetMapping("/test/getUser")
    public UserDO getUser() {
        StopWatch stopWatch = new StopWatch("get-user");
        stopWatch.start();
        UserDO userDO = (UserDO) SecurityUtils.getSubject().getSession().getAttribute("info");
        stopWatch.stop();
        log.debug(stopWatch.shortSummary());
        return userDO;
    }

    @GetMapping("/login/{userName}/{password}")
    public String helloGood(@PathVariable String userName, @PathVariable String password) {
        StopWatch stopWatch = new StopWatch("login");
        stopWatch.start();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password);
        subject.login(usernamePasswordToken);
        stopWatch.stop();
        log.debug(stopWatch.shortSummary());
        return "login successful";
    }
}